const router = require("koa-router")();

const UUID = require('uuid')

const ArticleReports = require('../../model/ArticleReports')
const ArticleAttitude = require('../../model/ArticleAttitude')
const ArticleCollect = require('../../model/ArticleCollect')
const UserBasic = require('../../model/UserBasic')
const { sendMessageByUserId } = require('../websocket')
const { getUserIdByContext, getDefaultMan, getImage } = require('../token');
const ArticleBasic = require("../../model/ArticleBasic");
const UserMessage = require("../../model/UserMessage");

// 对文章点赞
router.post('/likings', async ctx => {
  const user_id = await getUserIdByContext(ctx) // 获取用户id
  const { target } = ctx.request.body
  let sendObj = null
  if (target.startsWith('l-')) {
    // 如果是网络文章
    sendObj = {
      title: '网络文章',
      ...getDefaultMan(),
      timestamp: new Date().getTime(),
      art_id: target,
    }
  }else {
    let article = await ArticleBasic.findOne({ article_id: target }).lean()
    let userProfle = await UserBasic.findOne({ user_id: article.user_id  }).lean();
     sendObj = {
      user_id,
      user_name: userProfle.user_name,
      user_photo: getImage(userProfle.profile_photo),
      timestamp: new Date().getTime(),
      art_id: target,
      art_title: article.title
     }
       // 通知被关注的用户
  sendMessageByUserId(target, "liking notify", sendObj)
  const UserInfo = await UserBasic.findOne({ user_id })
  await UserMessage.create({ type: "4" , message_id: UUID.v4(), title: UserInfo.user_name, content: '赞了你的文章', user_id: article.user_id, comment_target:  article.title  })
  }
  
  ctx.status = 201
  return  await likeOrDisLike(user_id, target, 1)
})
// 取消文章点赞
router.delete('/likings/:target', async ctx => {
  const user_id = await getUserIdByContext(ctx) // 获取用户id
  const { target } = ctx.params
  ctx.status = 204
  return  await likeOrDisLike(user_id, target, -1)
})
// 对文章不喜欢
router.post('/dislikes', async ctx => {
  const user_id = await getUserIdByContext(ctx) // 获取用户id
  const { target } = ctx.request.body
  ctx.status = 201
  return  await likeOrDisLike(user_id, target, 0)
})
// 取消文章不喜欢
router.delete('/dislikes/:target', async ctx => {
  const user_id = await getUserIdByContext(ctx) // 获取用户id
  const { target } = ctx.params
  ctx.status = 204
  return  await likeOrDisLike(user_id, target, -1)
})
// 举报文章
router.post('/reports', async (ctx, next) => {
  const user_id = await getUserIdByContext(ctx) // 获取用户id
  const { target, type, remark } = ctx.request.body
  if (!user_id) {
    return { success: false, message: '用户未认证', status: 401 }
  }
  if (!target || !type) {
    return { success: false, message: '举报目标或者类型不能为空', status: 400 }
  }
 const report_id = UUID.v4() // uuid
 await ArticleReports.create({ report_id, user_id, article_id: target, type, remark })
 ctx.status = 201
 return  {
     data: {
         target, type
     }
 }
})
// 获取收藏列表
router.get('/collections', async ctx => {
  const user_id = await getUserIdByContext(ctx) // 获取用户id
  let { page = 1, per_page = 10 } = ctx.request.query
  page = parseInt(page)
  per_page = parseInt(per_page)
  if (!user_id) {
    return { success: false, message: '用户未认证', status: 401 }
  }
 const total_count = await ArticleCollect.find({ user_id }).countDocuments()
 let results =  await ArticleCollect.aggregate([{
    $lookup: {
      from: "news_article_basic",
      localField: "article_id",
      foreignField: "article_id",
      as: "articleInfo"
     }
  }, {
    $lookup: {
      from: "user_basic",
      localField: "user_id",
      foreignField: "user_id",
      as: "user"
    }
  },{
    $match: {
      user_id
    }
  },{
    $skip: (page - 1) * per_page
  }, {
    $limit: per_page
  }])
  results = results.map(item => ({
    art_id: item.article_id ,
    title: item.articleInfo && item.articleInfo.length ?  item.articleInfo[0].title : '',
    aut_id: item.user_id,
    comm_count: item.articleInfo && item.articleInfo.length ?  item.articleInfo[0].comment_count : 0 ,
    pubdate: item.articleInfo && item.articleInfo.length ?  item.articleInfo[0].create_time : '' ,
    aut_name: item.user && item.user.length ? item.user[0].user_name : '无名氏',
    is_top: 0,
    cover: { type: 0 },
    like_count: 0
  }))  
  ctx.status = 200
  return  { data: { page, per_page, results, total_count } }
})
// 收藏文章
router.post('/collections', async ctx => {
  const user_id = await getUserIdByContext(ctx) // 获取用户id
  const { target } = ctx.request.body
  if (!user_id) {
    return { success: false, message: '用户未认证', status: 401 }
  }
  if (!target) {
    return { success: false, message: '收藏目标或者类型不能为空', status: 400 }
  }
  await ArticleCollect.create({ user_id, article_id: target, collection_id: UUID.v4() })
  ctx.status = 201
  return  { data: { target } }
})
// 取消收藏文章
router.delete('/collections/:target', async ctx => {
  const user_id = await getUserIdByContext(ctx) // 获取用户id
  const { target } = ctx.params
  if (!user_id) {
    return { success: false, message: '用户未认证', status: 401 }
  }
  if (!target) {
    return { success: false, message: '收藏目标或者类型不能为空', status: 400 }
  }
  await ArticleCollect.findOneAndRemove({ user_id, article_id: target})
  ctx.status = 204
})
const  likeOrDisLike = async (user_id, target, attitude) => {
  if (!user_id) {
    return { success: false, message: '用户未认证', status: 401 }
  }
  if (!target) {
    return { success: false, message: '点赞的内容为空', status: 400 }
  }
 const likeOne = await ArticleAttitude.findOne({ user_id, article_id: target }).lean()
 if (!likeOne) {
   // 如果存在 表示已经点过暂了 如果不存在需要 创建一个记录
   await ArticleAttitude.create({ user_id, article_id: target, attitude })
 }else {
  await ArticleAttitude.findOneAndUpdate({user_id, article_id: target },{  attitude })
 }
 return  { data: { target } }
}
module.exports = router.routes();

// 时间戳